package com.craftworks.rtmp;

public class RtmpMessage
{
    private final int type;
    private final int bodySize;
    private final long streamID;
    private final byte[] body;
    private int offset;

    public RtmpMessage(int type, int length, long streamId)
    {
        this.type = type;
        this.bodySize = length;
        this.streamID = streamId;
        this.body = new byte[length];
        this.offset = 0;
    }

    public void fillChunk(Chunk chunk)
    {
        System.arraycopy(chunk.getData(), 0, body, offset, chunk.getBodySize());
        offset += chunk.getBodySize();
    }

    public int getType()
    {
        return type;
    }

    public long getStreamID()
    {
        return streamID;
    }

    public int getBodySize()
    {
        return bodySize;
    }

    public byte[] getBody()
    {
        return body;
    }

    public boolean isComplete()
    {
        return offset == bodySize;
    }

    @Override
    public String toString()
    {
        return "RtmpMessage{" +
               "type=" + type +
               ", bodySize=" + bodySize +
               ", streamID=" + streamID +
               '}';
    }

    public static RtmpMessage fromChunk(Chunk chunk)
    {
        RtmpMessage msg = new RtmpMessage(chunk.getMessageTypeID(), chunk.getMessageLength(), chunk.getMessageStreamID());
        msg.fillChunk(chunk);
        return msg;
    }
}
